package com.steveproject.parttimeworktree.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.steveproject.parttimeworktree.App;
import com.steveproject.parttimeworktree.R;
import com.steveproject.parttimeworktree.adapter.Part2PublicAdapter;
import com.steveproject.parttimeworktree.base.BaseActivity;
import com.steveproject.parttimeworktree.entity.DailyEntity;
import com.steveproject.parttimeworktree.entity.Part2JobEntity;
import com.steveproject.parttimeworktree.entity.PartBaseEntity;
import com.steveproject.parttimeworktree.myinterface.myLocation;
import com.steveproject.parttimeworktree.net.MyCallback;
import com.steveproject.parttimeworktree.net.NoValidationTask;
import com.steveproject.parttimeworktree.utils.GPSUtils;
import com.steveproject.parttimeworktree.utils.NewsToastUtils;
import com.steveproject.parttimeworktree.utils.PermissionUtils;
import com.steveproject.parttimeworktree.utils.SPUtils;
import com.steveproject.parttimeworktree.utils.TitleBuilder;
import com.steveproject.putorefresh.BaseBothListener;
import com.steveproject.putorefresh.PullToBothLayout;
import com.steveproject.putorefresh.ViewStatus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Response;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class Part2JobDetailActivity extends BaseActivity {
    private String type = "0";
    private String city = "";//城市信息

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;

    private int page = 1;
    private boolean isRefresh = true;
    private Part2PublicAdapter part2JobAdapter = null;
    private List<Part2JobEntity> list_jobs = new ArrayList<>();

    @Override
    public void setListen() {
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                page = 1;
                isRefresh = true;
                getSiftJobs();
            }

            @Override
            public void loadMore() {
                page++;
                isRefresh = false;
                getSiftJobs();
            }
        });
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_part2_detail;
    }

    @Override
    public void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        if (part2JobAdapter == null) {
            part2JobAdapter = new Part2PublicAdapter(Part2JobDetailActivity.this, list_jobs);
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(part2JobAdapter);
        part2JobAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(Part2JobDetailActivity.this, PartDetailActivity.class).putExtra("jobId", list_jobs.get(position).getJobId()));
            }
        });
    }

    //关闭下拉刷新
    private void closePullTo() {
        pullToBothLayout.finishRefresh();
        pullToBothLayout.finishLoadMore();
    }

    /**
     * 获取定位权限
     */
    private void getLocationPermission() {
        int flag = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (flag != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            getLocation();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PERMISSION_GRANTED) {
                getLocation();
            } else {
                NewsToastUtils.showToast(App.getContext(), "权限被拒绝！");
                pullToBothLayout.showView(ViewStatus.ERROR_STATUS);
                pullToBothLayout.getView(ViewStatus.ERROR_STATUS).findViewById(R.id.tv_withDrawNow).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //弹出开启权限
                        PermissionUtils.getInstance().showSystemPermissionsSettingDialog(Part2JobDetailActivity.this);
                    }
                });
            }
        }

    }

    //获取位置信息
    private void getLocation() {
        pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        //获取城市编码
        GPSUtils.getInstance(this).getLocation(new myLocation() {
            @Override
            public void onSuccess(String cc) {
                //获取成功开始获取内容
                city = cc;
                //获取职位列表
                getSiftJobs();
            }

            @Override
            public void onFail(int code) {
                //获取位置信息失败
                pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        assert type != null;
        //标题
        String title = "";
        switch (type) {
            case "0":
                title = "最新发布";
                break;
            case "1":
                title = "名企专区";
                break;
            case "2":
                title = "简单易做";
                break;
            case "3":
                title = "薪资最高";
                break;
            case "4":
                title = "离我最近";
                break;
            default:
                title = "最新发布";
                break;
        }
        new TitleBuilder(this).setTitleText(title)
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
        if (type.equals("4")) {
            getLocationPermission();
        } else {
            getSiftJobs();
        }
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    //获取对应的职位列表
    private void getSiftJobs() {
        if (isRefresh)
            pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        NoValidationTask.getApiService().getSiftJobs(userId, type, page, city).enqueue(new MyCallback<PartBaseEntity>(Part2JobDetailActivity.this,pullToBothLayout) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (isRefresh) {
                    list_jobs.clear();
                    if (jsonArray.size() > 0) {
                        pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list_jobs.add(part2JobEntity);
                        }

                    } else {
                        pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
                    }
                } else {
                    pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list_jobs.add(part2JobEntity);
                        }
                    }
                }
                part2JobAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {
                closePullTo();
            }
        });
    }
}
